package leetcode.t4LinkedList;

/**
 * @author K
 * @date 2024/1/16 15:59
 */
public class ListNode {
    public int val;
    public ListNode next;

    public ListNode() {
    }

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }


    public ListNode put(ListNode head, int value) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode node = dummy;
        while (node.next != null) {
            node = node.next;
        }
        node.next = new ListNode(value);

        return dummy.next;
    }

    public ListNode put2(ListNode head, int value) {
        ListNode newNode = new ListNode(value);
        if (head == null) {
            return newNode;
        }
        ListNode node = head;
        while (node.next != null) {
            node = node.next;
        }
        node.next = newNode;

        return node;
    }

    public ListNode delete(ListNode head, int value) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode node = dummy;
        while (node.next != null) {
            if (node.next.val == value) {
                node.next = node.next.next;
                break;
            }
            // 如果删除的是第一个，执行不到这里来，那么head还是没有变化；只是给node.next赋了一个新值，并没有给head赋值
            node = node.next;
            // 执行完赋值后，以后的node就指向了head，给node.next赋值后，也会修改head
        }

        return dummy.next;
    }

    public ListNode deletePlus(ListNode head, int value) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode node = dummy;
        while (node.next != null) {
            if (node.next.val == value) {
                node.next = node.next.next;
                break;
            }
            node = node.next;
        }
        // 重新给head赋值，dummy是另一个对象
        head = dummy.next;
        return head;
    }

    public ListNode delete2(ListNode head, int value) {
        if (head == null) {
            return null;
        }
        if (head.val == value) {
            return head.next;
        }

        ListNode node = head;
        while (node.next != null) {
            if (node.next.val == value) {
                node.next = node.next.next;
                break;
            }
            node = node.next;
        }

        return node;
    }

    public static void main(String[] args) {
        ListNode node = new ListNode(1);
        for (int i = 0; i < 5; i++) {
            node.put(node, i + 2);
//            node.put2(node, i + 1);
        }

        ListNode delete = node.delete(node, 2);
        ListNode delete2 = node.delete2(node, 1);
        ListNode deletePlus = node.deletePlus(node, 1);
        System.out.println();

    }
    
}
